<?php
class model_MessageMapper {
    private $table = 'messages';

    public function  __construct() {
        model_ConfigMapper::connect();
    }

    public function getTable() {
        return $this->table;
    }

    public function find($id, $user) { //находим сообщение, записываем его содержание в свойства объекта
        $query = 'SELECT * from '. $this->table .' WHERE id = '. $id;
        $result = mysql_query($query);
        $row = mysql_fetch_assoc($result);

        if ($row) {
            $m = new model_MessageModel($row);
            if($m->getKomu() == $user->getId() && 0 == $m->getIsread()) {
                $query = 'UPDATE '. $this->table .' SET isread = 1 WHERE id = '. $id;
                $result = mysql_query($query);

                $timer = model_ConfigMapper::instance();
                $timer->setSqlCounter();
            }
        } else {
            $m = new model_MessageModel(null);
        }

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        return $m;
    }

    public function fetchAll($id, $who, $start, $nums) { //
        $query = 'SELECT * from '. $this->table .' WHERE '. $who .' ='. $id .' ORDER BY id DESC LIMIT '. $start .', '. $nums ;
        $result = mysql_query($query);

        $entries = array();

        while ($row = mysql_fetch_assoc($result)) {
            $entry = new model_MessageModel($row);
            $entries[] = $entry;
        }

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
        return $entries;
    }

    public function save($model) {
        $query = 'INSERT INTO '.$this->table.' (text, kto, komu, date, isread) VALUES ("'. $model->getText() .'","'. $model->getKto() .'","'. $model->getKomu() .'","'. $model->getDate() .'","'. $model->getIsread() .'")';
        $result = mysql_query($query);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
    }

    public function delete($id) { // собственно удаляем
        $query = 'DELETE FROM '.$this->table.' WHERE id="'.$id.'"';
        $result = mysql_query($query);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
    }

    public function checkMsg($msg) {
        if ('' == $msg['text']) {
            $message = 'Вы отправляете пустое сообщение! ';
        }
        
        if (!empty($message)) {
            return $message;
        }
    }
}